import os

from flask import Blueprint
from webargs import fields
from webargs.flaskparser import use_args

from app.clients.device_client import login, query_list
from app.clients.table_store_client import ts_client
from app.models.device_info import DeviceInfo
from app.models.user_info import UserInfo
from onething_client import OnethingLogin

device = Blueprint('device', __name__)


@device.get('/discovery')
def device_discovery():
    device_info_list = ts_client.list(DeviceInfo)
    if device_info_list is not None:
        return [{
            "targets": [os.environ.get('TARGET_HOST')],
            "labels": {
                "__metrics_path__": f"/metrics/adapter/{device_info.number}"
            }
        } for device_info in device_info_list]

authorization_header_args = {
    'x-wx-openid': fields.Str(required=True, location='headers'),
}

device_authorization_args = {
    'tk': fields.Str(required=True, location='json'),
    'phone': fields.Str(required=True, location='json'),
    'smsCode': fields.Str(required=True, location='json'),
}


@device.post('/authorization')
@use_args(authorization_header_args)
@use_args(device_authorization_args)
def device_authorization(headers_json: dict,request_json: dict):
    user_token = login(**request_json)
    if user_token is not None:
        ts_client.save(user_token)
        user_info = UserInfo(
            open_id=headers_json.get('x-wx-openid'),
            phone_number=request_json.get('phone')
        )
        ts_client.save(user_info)
        device_models = query_list(user_token)
        for device_model in device_models:
            ts_client.save(device_model)


@device.post('/verification_code')
@use_args({'phone_number': fields.Str()}, location='json')
def get_verification_code(request_json):
    phone_number = request_json.get('phone_number')
    return OnethingLogin().send_verification_code(phone_number) if phone_number is not None else {}
